Star (-) Watch (-)

Blog

NodeJS module.exports

module.exports is the fundamental part of node.js. In Node, variables, functions, classes and class members are only visible in the same file. module.exports is the object that’s actually returned as the result of a require call.

helloworld.js
var hello = ‘hello ‘;
var print = function(name) {
return hello + name;
};

You cannot access the hello variable or hello function from outside the file. This has nothing to do with the use of the var keyword. Rather, the fundamental Node building block is called a module which maps directly to a file. So we could say that the above file corresponds to a module named “helloworld” and everything within that module is private. “require” is used to load a module, which is why its return value is typically assigned to a variable:

var helloworld = require(‘./helloworld’);

Note we are not using the file extension within the require. To expose the variables, functions, classes and class members we use module.exports.

var hello = ‘hello ‘;
var print = function(name) {
return hello + name;
};
module.exports.hello = hello;
module.exports.print = print;

So that we can call the function and the variable from other file using the below code

var helloworld = require(‘./helloworld’);
helloworld.hello = “welcome”;
console.log(helloworld.print());

There’s another way to expose things in a module:

var print = function(hello, name) {
this.hello = hello;
this.name = name;
};
module.exports = print;

Here we are exporting print directly, without any indirection. The difference between:

module.exports.print = print;

//vs

module.exports = print;

is all about how it’s used:

var helloworld = require(‘./helloworld’);
var hello = new helloworld.print();

//vs

var hello = new helloworld();

What happens when you directly export a function:

var print = function(hello, name) {
this.hello = hello;
this.name = name;
};

module.exports = print;

When you require the above file, the returned value is the actual function. This means that you can do:

require(‘./helloworld’)(‘hello’,’myname’);

Which is really just a condensed version of:

var helloworld = require(‘./helloworld’)
helloworld(‘hello’,’myname’);

require is a plain object whose properties may be accessed using the variable. If you overwrite exports then it will no longer refer to module.exports. So if you wish to assign a new object (or a function reference) to exports then you should also assign that new object to module.exports. The name assigned to exports object can be different from the internal function name.

var internalFunction = function() { … };
exports.aliasname = internalFunction;

Then to call the function

var m = require(‘mymodule’);
m.aliasname(); // invokes module.internalFunction